package com.hong.atomic;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Auther: Administrator
 * @Date: 2018/7/19 15:18
 * @Description: 自定义锁
 */
public class CompareAndSetLock {

    private final AtomicInteger value  = new AtomicInteger(0);

    private Thread lockedThread;

    public void tryLock() throws GetLockException{
        boolean flag = value.compareAndSet(0, 1);
        System.out.println(flag);
        if(!flag){
            throw  new GetLockException("get  the lock failed!");
        }else {
            lockedThread = Thread.currentThread();
        }

    }

    public void unlock(){
        if(0==value.get()){
            return;
        }

        if(lockedThread == Thread.currentThread()){
            value.compareAndSet(1,0);
        }


    }
}
